import { Component } from 'cc'

/**
 * Http 请求封装
 */
export class Request extends Component {
  /**
   * get请求
   * @param {string} url
   * @param {function} callback
   */
  httpGet(
    url: string,
    callback: (status: number, res?: object | null, respText?: string) => any
  ) {
    let xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      let readyState = xhr.readyState
      let status = xhr.status
      console.log(`[Request] get readyState: ${readyState}, status: ${status}`)
      if (readyState === 4 && status == 200) {
        let response = xhr.responseText
        let res = JSON.parse(response)
        callback(status, res, response)
      } else if (xhr.readyState === 4 && xhr.status == 401) {
        callback(401)
      } else {
        callback(-1)
      }
    }
    xhr.withCredentials = true
    xhr.open('GET', url, true)

    // if (cc.sys.isNative) {
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST')
    xhr.setRequestHeader(
      'Access-Control-Allow-Headers',
      'x-requested-with,content-type,authorization'
    )
    xhr.setRequestHeader('Content-Type', 'application/json')
    // xhr.setRequestHeader('Authorization', 'Bearer ' + cc.myGame.gameManager.getToken());
    // xhr.setRequestHeader('Authorization', 'Bearer ' + "");
    // }

    xhr.timeout = 8000
    xhr.send()
  }

  /**
   * post请求
   * @param {string} url
   * @param {object} params
   * @param {function} callback
   */
  httpPost(
    url: string,
    params: object,
    callback: (status: number, res?: object | null, respText?: string) => any
  ) {
    let xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      let readyState = xhr.readyState
      let status = xhr.status
      console.log(`[Request] post readyState: ${readyState}, status: ${status}`)
      if (readyState === 4 && status == 200) {
        let response = xhr.responseText
        let res = JSON.parse(response)
        callback(status, res, response)
      } else {
        callback(-1)
      }
    }
    xhr.open('POST', url, true)
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST')
    xhr.setRequestHeader(
      'Access-Control-Allow-Headers',
      'x-requested-with,content-type'
    )
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.timeout = 8000
    xhr.send(JSON.stringify(params))
  }
}
